//
//  MsgUserBaseCell.swift
//  swiftim
//
//  Created by yangjian on 2023/6/9.
//

import Foundation
import Kingfisher
import RxSwift
import HyphenateChat

class MsgUserBaseCell : MsgBaseCell {
    
//    var userInfoBag = DisposeBag()
    let customBackgroundView  = UIView()
    let headImageView  = UIImageView()

    let nameLabel  = UILabel()
    let msgBackgroundView  = UIView()
    let stateLabel  = UILabel()
    
    let msgContentView = UIView()
    let bubbleView  = BubbleView()


    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.configUserInfoViews()
    }
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    
    func configUserInfoViews(){
        //添加视图
        contentView.addSubview(customBackgroundView)
        customBackgroundView.addSubview(headImageView)
        customBackgroundView.addSubview(nameLabel)
        customBackgroundView.addSubview(msgBackgroundView)
        customBackgroundView.addSubview(stateLabel)
        msgBackgroundView.addSubview(msgContentView)
        
        //设置约束
        customBackgroundView.snp.makeConstraints { make in
            make.edges.equalTo(UIEdgeInsets.zero)
        }
        //关联交互
//        tapGesture.rx.event.subscribe(onNext: {[unowned self] element in
//        }).disposed(by: bag)
//        longPressGesture.rx.event.subscribe(onNext: {[unowned self] element in
//        }).disposed(by: bag)
        
        headImageView.isUserInteractionEnabled = true;
        let headTapGesture = UITapGestureRecognizer()
        headImageView.addGestureRecognizer(headTapGesture)
        headTapGesture.rx.event.subscribe(onNext: {[unowned self] sender in
            if sender.state == .ended {
                self.rx_msgEventSubject.onNext((self.model,self,MsgBaseCell.MsgCellEvent.headTap,""))
            }
        }).disposed(by: bag)

        let headLongPressGesture = UILongPressGestureRecognizer()
        headImageView.addGestureRecognizer(headLongPressGesture)
        headLongPressGesture.rx.event.subscribe(onNext: {[unowned self] sender in
            if sender.state == .began {
                self.rx_msgEventSubject.onNext((model,self,.headLongTap,""))
            }
        }).disposed(by: bag)
        
        let headDoubleTapGesture = UITapGestureRecognizer()
        headDoubleTapGesture.numberOfTapsRequired = 2
        headImageView.addGestureRecognizer(headDoubleTapGesture)
        headDoubleTapGesture.rx.event.subscribe(onNext: {[unowned self] sender in
            if sender.state == .ended {
                self.rx_msgEventSubject.onNext((self.model,self,MsgBaseCell.MsgCellEvent.headDoubleTap,""))
            }
        }).disposed(by: bag)

        //设置效果
        nameLabel.font = MsgTableViewConfig.share.nameFont
        stateLabel.font = MsgTableViewConfig.share.stateFont
        stateLabel.textColor = UIColor.gray
        
        headImageView.backgroundColor = UIColor.orange
        msgBackgroundView.backgroundColor = UIColor.orange
        msgContentView.backgroundColor = UIColor.yellow
        
    }

    func configBubbleView(superView : UIView,aboveView : UIView){
        superView.insertSubview(self.bubbleView, belowSubview: aboveView)
        
        self.bubbleView.rx_messageBubbleEventSubject.map { event in
            return (self.model,self,event,"")
        }.bind(to: self.rx_msgEventSubject).disposed(by: bag)

        
        
//        self.bubbleView.rx_msgBubbleMenuEventSubject.map {[unowned self] menuEvent in
//            return (self,self.model,menuEvent,"")
//        }.bind(to: self.rx_msgEventSubject).disposed(by: bag)
    }
    
    override func bindFromModel(_ model : MsgCellBaseModel){
        super.bindFromModel(model)
        var showName = false;
        var showHead = false;
        if self.model.message.chatType == .chat {
            if self.model.direction == .send {
                showName = MsgTableViewConfig.share.singleSend_showName
                showHead = MsgTableViewConfig.share.singleSend_showHead
            }else if self.model.direction == .receive {
                showName = MsgTableViewConfig.share.singleReceive_showName
                showHead = MsgTableViewConfig.share.singleReceive_showHead
            }else{}
        }else if self.model.message.chatType == .groupChat {
            if self.model.direction == .send {
                showName = MsgTableViewConfig.share.groupSend_showName
                showHead = MsgTableViewConfig.share.groupSend_showHead
            }else if self.model.direction == .receive {
                showName = MsgTableViewConfig.share.groupReceive_showName
                showHead = MsgTableViewConfig.share.groupReceive_showHead
            }else{}
        }else if self.model.message.chatType == .chatRoom {
            if self.model.direction == .send {
                showName = MsgTableViewConfig.share.chatroomSend_showName
                showHead = MsgTableViewConfig.share.chatroomSend_showHead
            }else if self.model.direction == .receive {
                showName = MsgTableViewConfig.share.chatroomReceive_showName
                showHead = MsgTableViewConfig.share.chatroomReceive_showHead
            }else{}
        }else{}
        resetSubViewsLayout(showName: showName, showHead: showHead)

        model.rx_userInfo.subscribe(onNext: {[unowned self] userInfo in
            var haveUserInfo = false
            if let username = userInfo.userId {
                if username.count > 0 {
                    haveUserInfo = true
                }
            }
            if haveUserInfo {
                if userInfo.nickname?.count ?? 0 > 0 {
                    self.nameLabel.text = userInfo.nickname
                }else{
                    self.nameLabel.text = model.message.from
                }
                self.headImageView.image = UIImage(named: "defaultHead");
                if let url = URL(string: userInfo.avatarUrl ?? "") {
//                    self.headImageView.kf.setImage(with: .network(ImageResource(downloadURL: url)))
                }
            }else{
                self.nameLabel.text = model.message.from
                self.headImageView.image = UIImage(named: "defaultHead");
            }
        }).disposed(by: reuseBag)
        

        model.rx_messageStatus.subscribe {[unowned self] status in
            print("消息状态===\(model.message.messageId)-\(status)")
            if model.message.chatType == .chat {
                if model.direction == .send {
                    stateLabel.isHidden = false
                    
                    if status == .pending {
                        self.stateLabel.text = "等待发送"
                    }else if status == .delivering {
                        self.stateLabel.text = "正在发送"
                    }else if status == .succeed {
                        if model.message.isReadAcked {
                            self.stateLabel.text = "已读"
                        }else{
                            self.stateLabel.text = "未读"
                        }
                    }else if status == .failed {
                        self.stateLabel.text = "发送失败"
                    }else{
                        self.stateLabel.text = "未知状态"
                    }
                }else{
                    stateLabel.isHidden = true
                }
            }
        }.disposed(by: reuseBag)
        
        
//        guard let userInfo = UserInfoStore.share.fetchUserInfo(username: model.message.from) else {
//            EMIMHelper.share.userinfoUpdateFinishSubject.subscribe(onNext: {[unowned self] usernames in
//                if usernames.contains(self.model.message.from) {
//                    self.userInfoBag = DisposeBag()
//                    if let response = UserInfoStore.share.fetchUserInfo(username: model.message.from) {
//
//                    }
//                }
//            }).disposed(by: userInfoBag)
//            UserInfoStore.share.fetchUserInfosFromServer(usernames: [self.model.message.from])
//            return
//        }
    }
    
    func resetSubViewsLayout(showName : Bool,showHead : Bool) {
        self.nameLabel.isHidden = !showName
        self.headImageView.isHidden = !showHead
        if self.model.direction == .send {
            if showName {
                self.nameLabel.snp.remakeConstraints { make in
                    make.top.equalTo(MsgCellLayoutAdapterConfig.share.userInfoLayoutAdapter.nameTop)
                    make.height.equalTo(MsgCellLayoutAdapterConfig.share.userInfoLayoutAdapter.nameHeight)
                    make.right.equalTo(0 - (MsgCellLayoutAdapterConfig.share
                                              .userInfoLayoutAdapter.nameFromSide
                                              + (showHead ? MsgCellLayoutAdapterConfig.share
                                                 .userInfoLayoutAdapter.headTakeWidth() : 0)));
                }
            }
            if showHead {
                self.headImageView.snp.remakeConstraints { make in
                    make.top.equalTo(MsgCellLayoutAdapterConfig.share.userInfoLayoutAdapter.headTop);
                    make.width.equalTo(MsgCellLayoutAdapterConfig.share.userInfoLayoutAdapter.headWidth);
                    make.height.equalTo(MsgCellLayoutAdapterConfig.share.userInfoLayoutAdapter.headHeight);
                    make.right.equalTo(0 - MsgCellLayoutAdapterConfig.share
                                           .userInfoLayoutAdapter.headFromSide);
                    }
                }
        }else if self.model.direction == .receive {
            if showName {
                self.nameLabel.snp.remakeConstraints { make in
                    make.top.equalTo(MsgCellLayoutAdapterConfig.share.userInfoLayoutAdapter.nameTop)
                    make.height.equalTo(MsgCellLayoutAdapterConfig.share.userInfoLayoutAdapter.nameHeight)
                    make.left.equalTo(MsgCellLayoutAdapterConfig.share
                        .userInfoLayoutAdapter.nameFromSide
                                      + (showHead ? MsgCellLayoutAdapterConfig.share
                                        .userInfoLayoutAdapter.headTakeWidth() : 0));
                }
            }
            if showHead {
                self.headImageView.snp.remakeConstraints { make in
                    make.top.equalTo(MsgCellLayoutAdapterConfig.share.userInfoLayoutAdapter.headTop);
                    make.width.equalTo(MsgCellLayoutAdapterConfig.share.userInfoLayoutAdapter.headWidth);
                    make.height.equalTo(MsgCellLayoutAdapterConfig.share.userInfoLayoutAdapter.headHeight);
                    make.left.equalTo(MsgCellLayoutAdapterConfig.share
                        .userInfoLayoutAdapter.headFromSide);
                }
            }
        }else{}
        
        let msgbgTop = MsgCellLayoutAdapterConfig.share.backgroundLayoutAdapter.top + (showName ? MsgCellLayoutAdapterConfig.share.userInfoLayoutAdapter.nameTakeHeight() : 0)
        let msgbgBottom = MsgCellLayoutAdapterConfig.share.backgroundLayoutAdapter.bottom
        let msgbgFromSide = MsgCellLayoutAdapterConfig.share.backgroundLayoutAdapter.fromSide + (showHead ? MsgCellLayoutAdapterConfig.share.userInfoLayoutAdapter.headTakeWidth() : 0)
        let msgbgToSide = MsgCellLayoutAdapterConfig.share.backgroundLayoutAdapter.toSide + (showHead ? 0 : MsgCellLayoutAdapterConfig.share.userInfoLayoutAdapter.headTakeWidth())
        let msgBackgroundEdgeInsets = convertToEdgeInsets_direction(
            direction: self.model.direction,
            top: msgbgTop,
            bottom: msgbgBottom,
            fromSide: msgbgFromSide,
            toSide: msgbgToSide)
        
        msgBackgroundView.snp.remakeConstraints { make in
            make.top.equalTo(msgBackgroundEdgeInsets.top);
            make.left.equalTo(msgBackgroundEdgeInsets.left);
            //自动计算高度时,需要下面这行约束
            //make.bottom.equalTo(-msgBackgroundEdgeInsets.bottom);
            make.right.equalTo(-msgBackgroundEdgeInsets.right);
        }
        if self.model.msgBodyType != .voice {
            if self.model.direction == .send {
                msgContentView.snp.remakeConstraints { make in
                    make.top.equalTo(MsgCellLayoutAdapterConfig.share.contentLayoutAdapter.top)
                    make.bottom.equalTo(-MsgCellLayoutAdapterConfig.share.contentLayoutAdapter.bottom);
                    make.left.greaterThanOrEqualTo(MsgCellLayoutAdapterConfig.share.contentLayoutAdapter.toSide)
                    make.right.equalTo(-MsgCellLayoutAdapterConfig.share.contentLayoutAdapter.fromSide)
                }
            }else if self.model.direction == .receive {
                msgContentView.snp.remakeConstraints { make in
                    make.top.equalTo(MsgCellLayoutAdapterConfig.share.contentLayoutAdapter.top)
                    make.bottom.equalTo(-MsgCellLayoutAdapterConfig.share.contentLayoutAdapter.bottom);
                    make.left.equalTo(MsgCellLayoutAdapterConfig.share.contentLayoutAdapter.fromSide)
                    make.right.lessThanOrEqualTo(-MsgCellLayoutAdapterConfig.share.contentLayoutAdapter.toSide)
                }
            }else{}
        }
    }
    
    func resetBubbleleView(aboveView : UIView){
        let bubbleEdgeInsets =
        convertToEdgeInsets_direction(direction: model.direction, top: MsgCellBubbleLayoutAdapterConfig.share.currentAdapter().top, bottom: MsgCellBubbleLayoutAdapterConfig.share.currentAdapter().bottom, fromSide: MsgCellBubbleLayoutAdapterConfig.share.currentAdapter().fromSide, toSide: MsgCellBubbleLayoutAdapterConfig.share.currentAdapter().toSide)
        bubbleView.snp.remakeConstraints { make in
            make.top.equalTo(aboveView).offset(-bubbleEdgeInsets.top)
            make.bottom.equalTo(aboveView).offset(bubbleEdgeInsets.bottom)
            make.left.equalTo(aboveView).offset(-bubbleEdgeInsets.left)
            make.right.equalTo(aboveView).offset(bubbleEdgeInsets.right)
        }
        self.bubbleView.image = MsgCellBubbleLayoutAdapterConfig.share.currentAdapter().bubbleImage(direction: model.direction);
//        self.bubbleView.bodyType = self.model.msgBodyType
    }
}
